package ge.unihack.instantdj.protocol.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.util.Log;

class ClientListenerThread extends Thread {

	private static final String TAG = "ClientListenerThread";
	private ServerSocket sock;
	private boolean listening;
	private ClientListener clientListener;
	private ClientReader clientReader = new JSONClientReader();

	public ClientListenerThread(ClientListener clientListener) {
		this.clientListener = clientListener;
	}

	int startListening() throws IOException {
		if (sock == null) {
			sock = new ServerSocket(0);
			start();
			listening = true;
		}
		return sock.getLocalPort();
	}

	@Override
	public void run() {
		while (listening) {
			try {
				Socket socketClient = sock.accept();
				InputStream in = socketClient.getInputStream();
				Client originalClient = clientReader.readClient(in);
				if (originalClient != null) {
					clientListener.onClientConnected(new ClientWrapper(originalClient, socketClient));
				} else {
					safeClose(socketClient);
				}
			} catch (IOException e) {
				Log.e(TAG, "Error while accepting client");
			}
		}
	}

	private void safeClose(Socket socket) {
		try {
			socket.close();
		} catch (IOException e) {
		}
	}
	
	public void stopListening() {
		if (sock != null) {
			listening = false;
			try {
				sock.close();
			} catch (IOException e) {

			}
			sock = null;
		}
	}

}